﻿using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerSocket.common
{
    class Message
    {

        public byte[] Data = new byte[1024];

        public int StartIndex = 0;

        public int LastIndex
        {
            get { return Data.Length - StartIndex; }
        }

        internal void ReadMessage(int newDataAmont, Action<string> OnProcessMessage)
        {
            StartIndex += newDataAmont;
            while (true)
            {
                if (StartIndex <= 4)
                {
                    return;
                }
                int count = BitConverter.ToInt32(Data, 0);
                if ((StartIndex - 4) >= count)
                {
                    string data = Encoding.UTF8.GetString(Data, 4, count);
                    OnProcessMessage(data);
                    Array.Copy(Data, count + 4, Data, 0, StartIndex - 4 - count);
                    StartIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }

        }

        /// <summary>
        /// 打包数据向客户端相应
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] PackData(string data)
        {
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            int dataAmount = dataBytes.Length;
            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);
            return dataAmountBytes.Concat(dataBytes).ToArray();
        }

        /// <summary>
        /// 打包数据向客户端相应(序列化)
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] PackData<T>(T data)
        {
            string jsonData = JsonMapper.ToJson(data);
            byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData);
            int dataAmount = dataBytes.Length;
            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);
            return dataAmountBytes.Concat(dataBytes).ToArray();
        }

    }
}
